// import { pick } from '@/util'
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { RootState } from '../index'
import { getToken, setTokens, removeTokens } from '@/util'
import { UserInfos } from '@/api/login'


export type Role = 'student' | 'admin' | 'super_admin'
interface UserInfo {
	realName: string,
	headUrl: string,
	id: string,
	userAccount: string
}
interface mytype {
	token: string
	userInfo: UserInfo
}


export type RoleState = mytype

// 数据持久化
const getUsers = () => {
	const data: string = localStorage.getItem('USER') || ''
	let obj: RoleState = {
		token: getToken() || '',
		userInfo: data ? JSON.parse(data) : {
			realName: '',
			headUrl: '',
			id: '',
			userAccount: '',
		}

	}
	return obj
}
// ---异步请求
export const fetchData = createAsyncThunk(
	'data/fetch', // 唯一标识符
	async () => {
		const response = await UserInfos();
		return response.data;
	}
);
// 创建单独的reduces
export const userlice = createSlice({
	name: 'user',
	initialState: getUsers,//初始化的值
	reducers: {//reduces ----同步的
		logout(state, aciton) {
			removeTokens()
			state = {
				token: '',
				userInfo: {
					realName: '',
					headUrl: '',
					id: '',
					userAccount: '',
				}
			}
		},
		setToken(state, { payload }) {
			setTokens(payload)
			state.token = payload
		}
	},
	extraReducers: (builder) => {
		// 处理结果，设置值
		builder.addCase(fetchData.fulfilled, (state, action) => {
			if (action.payload) {
				localStorage.setItem('USER', JSON.stringify(action.payload))
				Object.assign(state, action.payload)
			}

		})
	},
 

})

// 导出state数据-redux中content,里的第一参数
export const users = (state: RootState) => state
// 处理成这样类型：{payload: null,type: "user/login",}
export const { logout, setToken } = userlice.actions
export default userlice.reducer